<?php

/**
 * SiteController is the default controller to handle user requests.
 */
class RequestBookingController extends CController
{
	public $layout='management';
	private $_model;

	/**
	 * Index action is the default action in a controller.
	 */
	public function actionIndex()
	{
		//$now = new DateTime();
		//echo $now->format('Y-m-d H:i:s');    // MySQL datetime format

		// Authen Login
		if(!UserLoginUtil::isLogin()){
			$this->redirect(Yii::app()->createUrl('management/login'));
		}
		if(!UserLoginUtil::hasPermission(array("FULL_ADMIN", "VIEW_REQUEST_BOOKING", "VIEW_ALL_REQUEST_BOOKING", "CREATE_REQUEST_BOOKING", "UPDATE_REQUEST_BOOKING", "DELETE_REQUEST_BOOKING"))){
			throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested',
					array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
		}
		// Render
		$model = new RequestBooking();
		//$model->clearDateFilter();
		if(isset($_GET['year_filter'])){
			$model->year_filter = addslashes($_GET['year_filter']);
		}
		if(isset($_GET['month_filter'])){
			$model->month_filter = addslashes($_GET['month_filter']);
		}
		if(isset($_GET['day_filter'])){
			$model->day_filter = addslashes($_GET['day_filter']);
		}
		if(isset($_GET['status_filter'])){
			$model->status_filter = addslashes($_GET['status_filter']);
		}
		if(isset($_GET['room_filter'])){
			$model->room_filter = addslashes($_GET['room_filter']);
		}
		if(isset($_GET['user_filter'])){
			$model->user_filter = addslashes($_GET['user_filter']);
		}
		if(strtotime($model->year_filter."-".$model->month_filter."-".$model->day_filter) == strtotime(date("Y-m-d"))) {
			$model->hiddenPass = true;
		}


		$model2 = new RequestBooking();
		//$model2->clearDateFilter();
		if(isset($_GET['year_filter2'])){
			$model2->year_filter = addslashes($_GET['year_filter2']);
		}
		if(isset($_GET['month_filter2'])){
			$model2->month_filter = addslashes($_GET['month_filter2']);
		}
		if(isset($_GET['day_filter2'])){
			$model2->day_filter = addslashes($_GET['day_filter2']);
		}
		if(isset($_GET['status_filter2'])){
			$model2->status_filter = addslashes($_GET['status_filter2']);
		}
		if(isset($_GET['room_filter2'])){
			$model2->room_filter = addslashes($_GET['room_filter2']);
		}
// 		if(isset($_GET['user_filter2'])){
// 			$model2->user_filter = addslashes($_GET['user_filter2']);
// 		}
		$model2->user_filter = UserLoginUtil::getUserLoginId();
		if(strtotime($model2->year_filter."-".$model2->month_filter."-".$model2->day_filter) == strtotime(date("Y-m-d"))) {
			$model2->hiddenPass = true;
		}
		$userLogin = UserLoginUtil::getUserLogin();
		if($userLogin->role_id == '1' || $userLogin->role_id == '2') {
				
			$model->view_all_admin = true;
			$model->view_all_request = true;
				
			$model2->view_all_admin = false;
			$model2->view_all_request = false;

		} else {
			//if(UserLoginUtil::hasPermission(array("FULL_ADMIN","VIEW_ALL_REQUEST_BOOKING"))){
			$model2->view_all_request = false;
			//$model2->view_all_request = true;
			//}

		}

		$this->render('main', array('data'=>$model, 'data2'=>$model2));
	}

	public function actionApprove()
	{
		// Authen Login
		if(!UserLoginUtil::isLogin()){
			$this->redirect(Yii::app()->createUrl('management/login'));
		}
		if(!UserLoginUtil::hasPermission(array("FULL_ADMIN", "EDIT_REQUEST_BOOKING"))){
			throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested',
					array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
		}
		// Render
		$model = new RequestBooking();
		$model->clearDateFilter();
		$model->view_all_request = true;
		$model->status_filter = 'REQUEST_WAIT_APPROVE';
		$this->render('approve', array('data'=>$model));
	}

	public function actionApproveRequest()
	{
		// Authen Login
		if(!UserLoginUtil::isLogin()){
			$this->redirect(Yii::app()->createUrl('management/login'));
		}
		if(!UserLoginUtil::hasPermission(array("FULL_ADMIN", "EDIT_REQUEST_BOOKING"))){
			throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested',
					array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
		}

		if(isset($_GET['id'])) {
			$id = addslashes($_GET['id']);
			$model = RequestBooking::model()->findByPk($id);
			if(isset($model)) {
				$model->status_code = 'REQUEST_APPROVE';
				if($model->update()) {
					//ส่งเมล
					$content = 'Hi ' . $model->user_login->user_information->first_name.', You have booked the room.<br />'.
							'Here is your booking details.<br />'.
							'Booking Type : '.$model->request_booking_type->name.'<br />'.
							'Room Number : '.$model->room->name.'<br />'.
							'Course Name : '.$model->course_name.'<br />'.
							'Use Date : '.($model->request_date == null ? $model->day_in_week->name : DateTimeUtil::getDateFormat($model->request_date, "dd MM yyyy")).'<br />'.
							'Use Time : '.DateTimeUtil::getTimeFormat($model->period_s->start_hour, $model->period_s->start_min)." - ".DateTimeUtil::getTimeFormat($model->period_e->end_hour, $model->period_e->end_min).'<br />'.
							'The room will prepare for you 30 minutes before useing time.<br />'.
							'Best Regards.';
					if(isset($model->user_login->email)) {
						MailUtil::sendMail($model->user_login->email, 'Support AV-Online, Request Booking Result', $content);
					}
				}
			}
		}
		$this->redirect(Yii::app()->createUrl('RequestBooking/Approve'));
	}

	public function actionDisapproveRequest()
	{
		// Authen Login
		if(!UserLoginUtil::isLogin()){
			$this->redirect(Yii::app()->createUrl('management/login'));
		}
		if(!UserLoginUtil::hasPermission(array("FULL_ADMIN", "EDIT_REQUEST_BOOKING"))){
			throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested',
					array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
		}

		if(isset($_GET['id'])) {
			$id = addslashes($_GET['id']);
			$model = RequestBooking::model()->findByPk($id);
			if(isset($model)) {
				$model->status_code = 'REQUEST_CANCEL';
				if($model->update()) {
					//ส่งเมล
				}
			}
		}
		$this->redirect(Yii::app()->createUrl('RequestBooking/Approve'));
	}

	public function actionCheckStatus()
	{
		// Authen Login
		if(!UserLoginUtil::isLogin()){
			$this->redirect(Yii::app()->createUrl('management/login'));
		}
		if(isset($_SESSION['date_filter'])){
			$_GET['date_filter'] = $_SESSION['date_filter'];
		}
		if(isset($_SESSION['equipment_type_id'])){
			$_GET['equipment_type_id'] = $_SESSION['equipment_type_id'];
		}
		if(isset($_SESSION['start_period'])){
			$_GET['start_period'] = $_SESSION['start_period'];
		}

		$this->render('check_status');
	}

	public function actionCheckStatusMeeting()
	{
		// Authen Login
		if(!UserLoginUtil::isLogin()){
			$this->redirect(Yii::app()->createUrl('management/login'));
		}
		$this->render('check_status_meeting');
	}

	public function actionRequest()
	{
		// Authen Login
		if(!UserLoginUtil::isLogin()){
			$this->redirect(Yii::app()->createUrl('management/login'));
		}
		if(!UserLoginUtil::hasPermission(array("FULL_ADMIN", "CREATE_REQUEST_BOOKING"))){
			throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested',
					array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
		}

		if(isset($_POST['ajax']) && $_POST['ajax']==='user-registration-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		if(isset($_GET['room'])){
			$_SESSION['request_room'] = addslashes($_GET['room']);
			//$_SESSION['request_type'] = '1';
		} else {
			unset($_SESSION['request_room']);
		}
		if(isset($_POST['add_request'])){
			$transaction = Yii::app()->db->beginTransaction();
			$equipments = $_POST['equipments'];
			// Add Request
			$requestBooking = new RequestBooking();
			$requestBooking->attributes = $_POST['RequestBooking'];
			$requestBooking->user_login_id = UserLoginUtil::getUserLoginId();
			if($requestBooking->request_booking_type_id == 1||$requestBooking->request_booking_type_id == 2) {
				$requestBooking->status_code = "REQUEST_APPROVE";
			} else {
				$requestBooking->status_code = "REQUEST_WAIT_APPROVE";
			}
			$requestBooking->create_date = date("Y-m-d H:i:s");
			$validated = true;

			//เช็ค จบ ต้องไม่น้อยกว่า เริ่ม
			if($requestBooking->period_end < $requestBooking->period_start) {
				$validated = false;
				$result = array();
				$result['class'] = 'error';
				$result['message'] = 'Wrong period.';
				$_SESSION['OPERATION_RESULT'] = $result;
			}
			
			// เช็คต้องจองก่อน 30 นาที
			if($requestBooking->request_booking_type_id != '2') {
				if((strtotime($requestBooking->request_date.' '.DateTimeUtil::getTimeFormat($requestBooking->period_s->start_hour, $requestBooking->period_s->start_min).':00')) < (time() + 1800)) {
					$validated = false;
					$result = array();
					$result['class'] = 'error';
					$result['message'] = 'Must booking before start time 30 minutes.';
					$_SESSION['OPERATION_RESULT'] = $result;
				}
			}
			$addSuccess = true;
			if($requestBooking->request_booking_type_id == '2') {
				$condition = "(((".$requestBooking->period_start." between t.period_start and t.period_end or ".$requestBooking->period_end." between t.period_start and t.period_end) AND DAYOFWEEK(t.request_date) = '".$requestBooking->request_day_in_week."' and t.request_date between semester.start_date and semester.end_date  OR t.period_start BETWEEN ".$requestBooking->period_start." AND ".$requestBooking->period_end." OR t.period_end BETWEEN ".$requestBooking->period_start." AND ".$requestBooking->period_end.") OR ('".$requestBooking->semester_id."' = t.semester_id and (".$requestBooking->period_start." between t.period_start AND t.period_end or ".$requestBooking->period_end." between t.period_start and t.period_end  OR t.period_start BETWEEN ".$requestBooking->period_start." AND ".$requestBooking->period_end." OR t.period_end BETWEEN ".$requestBooking->period_start." AND ".$requestBooking->period_end."))) AND t.room_id = '".$requestBooking->room_id."'";
			} else {
				$dayOfWeek = date('w', strtotime($requestBooking->request_date));
				$condition = "((t.request_date='".$requestBooking->request_date."' and (".$requestBooking->period_start." between t.period_start and t.period_end or ".$requestBooking->period_end." between t.period_start and t.period_end OR t.period_start BETWEEN ".$requestBooking->period_start." AND ".$requestBooking->period_end." OR t.period_end BETWEEN ".$requestBooking->period_start." AND ".$requestBooking->period_end.")) OR ('".$requestBooking->request_date."' between semester.start_date and semester.end_date and '".($dayOfWeek + 1)."' = t.request_day_in_week AND ((".$requestBooking->period_start." between t.period_start and t.period_end or ".$requestBooking->period_end." between t.period_start and t.period_end OR t.period_start BETWEEN ".$requestBooking->period_start." AND ".$requestBooking->period_end." OR t.period_end BETWEEN ".$requestBooking->period_start." AND ".$requestBooking->period_end.") ))) AND '".$requestBooking->room_id."' = t.room_id";

			}
			$requestBookings = RequestBooking::model()->with('semester')->findAll(array(
					'condition'=>$condition));
			if(isset($requestBookings) && count($requestBookings) > 0) {
				$_SESSION['error'] = "The request time is not available.";
				$_SESSION['sql'] = $condition;

				$this->redirect(Yii::app()->createUrl('RequestBooking/Request'));
			}
			if($requestBooking->semester_id == 'undefined') {
				$requestBooking->semester_id = null;
			}
			if($requestBooking->request_date == 'undefined') {
				$requestBooking->request_date = null;
			}
			if($requestBooking->request_day_in_week == 'undefined') {
				$requestBooking->request_day_in_week = null;
			}
			if($validated && $requestBooking->save()){
				if(isset($equipments)) {
					foreach ($equipments as $equipment){
						$equipmentTypeId = addslashes($equipment);
						$requestBookingEquipmentType = new RequestBookingEquipmentType();
						$requestBookingEquipmentType->request_booking_id = $requestBooking->getPrimaryKey();
						$requestBookingEquipmentType->equipment_type_id = $equipmentTypeId;
						if(isset($_POST['EquipmentType'][$equipmentTypeId])){
							$requestBookingEquipmentType->quantity = addslashes($_POST['EquipmentType'][$equipmentTypeId]);
						}
						if(!$requestBookingEquipmentType->save()){
							$addSuccess = false;
							break;
						}
					}
				}
				if($requestBooking->request_booking_type_id == '3'){
					$requestBookingActivityDetail = new RequestBookingActivityDetail();
					$requestBookingActivityDetail->attributes = $_POST['RequestBookingActivityDetail'];
					$requestBookingActivityDetail->id = $requestBooking->getPrimaryKey();
					if($requestBookingActivityDetail->save()){
						$presentTypes = $_POST['present_type'];
						foreach ($presentTypes as $presentType){
							$presentTypeId = addslashes($presentType);
							$requestBookingActivityPresentType = new RequestBookingActivityPresentType();
							$requestBookingActivityPresentType->request_booking_activity_id = $requestBookingActivityDetail->getPrimaryKey();
							$requestBookingActivityPresentType->present_type_id = $presentTypeId;

							if(!$requestBookingActivityPresentType->save()){
								$addSuccess = false;
								break;
							}
						}
					}
				}
				$model = $requestBooking;
				$content = 'Hi ' . $model->user_login->user_information->first_name.', You have booked the room.<br />'.
						'Here is your booking details.<br />'.
						'Booking Type : '.$model->request_booking_type->name.'<br />'.
						'Room Number : '.$model->room->name.'<br />'.
						'Course Name : '.$model->course_name.'<br />'.
						'Use Date : '.($model->request_date == null ? $model->day_in_week->name : DateTimeUtil::getDateFormat($model->request_date, "dd MM yyyy")).'<br />'.
						'Use Time : '.DateTimeUtil::getTimeFormat($model->period_s->start_hour, $model->period_s->start_min)." - ".DateTimeUtil::getTimeFormat($model->period_e->end_hour, $model->period_e->end_min).'<br />'.
						'The room will prepare for you 30 minutes before useing time.<br />'.
						'Best Regards.';
				if(isset($model->user_login->email)) {
					echo 'Send Email Result:'.MailUtil::sendMail($model->user_login->email, 'Support AV-Online, Request Booking Result', $content);
				}
			} else {
				$addSuccess = false;
				if(!isset($_SESSION['OPERATION_RESULT'])) {
					$result = array();
					$result['class'] = 'error';
					$result['message'] = 'Save Fail.';
					$_SESSION['OPERATION_RESULT'] = $result;
				}
			}
			if($addSuccess) {
				$transaction->commit();
				$this->redirect(Yii::app()->createUrl('RequestBooking/View/id/'.$requestBooking->getPrimaryKey()));
			} else {
				$transaction->rollback();
				$model = new RequestBooking();
				$this->render('request', array('data'=>$model));
			}

		} else {
			// Render
			$model = new RequestBooking();
			$this->render('request', array('data'=>$model));
		}
	}

	public function actionView()
	{
		// Authen Login
		if(!UserLoginUtil::isLogin()){
			$this->redirect(Yii::app()->createUrl('management/login'));
		}
		if(!UserLoginUtil::hasPermission(array("FULL_ADMIN", "VIEW_REQUEST_BOOKING", "VIEW_ALL_REQUEST_BOOKING"))){
			throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested',
					array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
		}
		// Render
		$model = $this->loadModel();
		if(!UserLoginUtil::hasPermission(array("FULL_ADMIN", "VIEW_ALL_REQUEST_BOOKING")) && $model->user_login_id != UserLoginUtil::getUserLoginId()){
			throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested',
					array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
		}
		$this->render('view', array('data'=>$model));
	}

	public function actionConfirm()
	{
		// Authen Login
		if(!UserLoginUtil::isLogin()){
			$this->redirect(Yii::app()->createUrl('management/login'));
		}
		if(!UserLoginUtil::hasPermission(array("FULL_ADMIN", "CREATE_REQUEST_BOOKING"))){
			throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested',
					array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
		}
		// Render
		$model = $this->loadModel();
		if(!UserLoginUtil::hasPermission(array("FULL_ADMIN", "VIEW_ALL_REQUEST_BOOKING")) && $model->user_login_id != UserLoginUtil::getUserLoginId()){
			throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested',
					array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
		}
		if(isset($_POST['confirm'])){
			if($_POST['confirm'] == 'Confirm') {
				if($model->request_booking_type_id == 1 ||$model->request_booking_type_id == 2 ) {
					$model->status_code = "REQUEST_APPROVE";
				} else {
					$model->status_code = "REQUEST_WAIT_APPROVE";
				}
				if($model->update()){
					$content = 'Hi ' . $model->user_login->user_information->first_name.', You have booked the room.<br />'.
							'Here is your booking details.<br />'.
							'Booking Type : '.$model->request_booking_type->name.'<br />'.
							'Room Number : '.$model->room->name.'<br />'.
							'Course Name : '.$model->course_name.'<br />'.
							'Use Date : '.($model->request_date == null ? $model->day_in_week->name : DateTimeUtil::getDateFormat($model->request_date, "dd MM yyyy")).'<br />'.
							'Use Time : '.DateTimeUtil::getTimeFormat($model->period_s->start_hour, $model->period_s->start_min)." - ".DateTimeUtil::getTimeFormat($model->period_e->end_hour, $model->period_e->end_min).'<br />'.
							'The room will prepare for you 30 minutes before useing time.<br />'.
							'Best Regards.';
					if(isset($model->user_login->email)) {
						MailUtil::sendMail($model->user_login->email, 'Support AV-Online, Request Booking Result', $content);
					}
					$this->redirect(Yii::app()->createUrl('RequestBooking/View/id/'.$model->id));
				}
				// Mail

			} else if($_POST['confirm'] == 'Cancel'){
				if($model->delete()){
					$this->redirect(Yii::app()->createUrl('RequestBooking/'));
				}
			}
		}

		$this->render('confirm', array('data'=>$model));
	}

	public function actionUpdate()
	{
		// Authen Login
		if(!UserLoginUtil::isLogin()){
			$this->redirect(Yii::app()->createUrl('management/login'));
		}
		if(!UserLoginUtil::hasPermission(array("FULL_ADMIN", "UPDATE_REQUEST_BOOKING"))){
			throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested',
					array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
		}
		$model = $this->loadModel();
		if(isset($_POST['change_status'])){
			$status = addslashes($_POST['status_code']);
			$oldStatus = $model->status_code;
			$oldStatusName = $model->status->name;
			$model->status_code = $status;
			if($model->update()){
				$model = RequestBooking::model()->findByPk($model->id);
				if($oldStatus != $status) {
					$content = 'Hi ' . $model->user_login->user_information->first_name.', Your request booking with information below.<br />'.
							'Booking details.<br />'.
							'Booking Type : '.$model->request_booking_type->name.'<br />'.
							'Room Number : '.$model->room->name.'<br />'.
							'Course Name : '.$model->course_name.'<br />'.
							'Use Date : '.($model->request_date == null ? $model->day_in_week->name : DateTimeUtil::getDateFormat($model->request_date, "dd MM yyyy")).'<br />'.
							'Use Time : '.DateTimeUtil::getTimeFormat($model->period_s->start_hour, $model->period_s->start_min)." - ".DateTimeUtil::getTimeFormat($model->period_e->end_hour, $model->period_e->end_min).'<br />'.
							'Has been change status from "'.$oldStatusName.'" to "'.$model->status->name.'".<br />'.
							'Best Regards.';
					if(isset($model->user_login->email)) {
						MailUtil::sendMail($model->user_login->email, 'Support AV-Online, Request Booking Change Info', $content);
					}
				}
				$this->redirect(Yii::app()->createUrl('RequestBooking/'));
			} else {
				$this->render('update', array('data'=>$model));
			}
		} else {
			// Render
			$this->render('update', array('data'=>$model));
		}
	}

	public function actionCancel()
	{
		// Authen Login
		if(!UserLoginUtil::isLogin()){
			$this->redirect(Yii::app()->createUrl('management/login'));
		}
		if(!UserLoginUtil::hasPermission(array("FULL_ADMIN", "CREATE_REQUEST_BOOKING"))){
			throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested',
					array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
		}
		$model = $this->loadModel();
		$time = strtotime($model->request_date.' '.$model->period_s->start_hour.':'.$model->period_s->start_min.':00');
		if(($time - time()) > (30 * 60)) {
			$model->status_code = "REQUEST_CANCEL";
			if($model->update()){
				$this->redirect(Yii::app()->createUrl('RequestBooking/View/id/'.$model->id));
			}
		}
		// Render
		$this->render('view', array('data'=>$model));
	}

	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=RequestBooking::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}


}